<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI聊天测试界面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .chat-container {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 800px;
            height: 600px;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            backdrop-filter: blur(10px);
        }

        .chat-header {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            padding: 20px;
            text-align: center;
            position: relative;
        }

        .chat-header h1 {
            font-size: 24px;
            margin-bottom: 5px;
        }

        .chat-header p {
            opacity: 0.9;
            font-size: 14px;
        }

        .connection-status {
            position: absolute;
            top: 15px;
            right: 20px;
            display: flex;
            align-items: center;
            font-size: 12px;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 5px;
        }

        .status-connected { background: #4CAF50; }
        .status-error { background: #f44336; }
        .status-loading { background: #ff9800; }

        .config-panel {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #e9ecef;
            display: flex;
            gap: 15px;
            align-items: center;
            flex-wrap: wrap;
        }

        .config-input {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 6px;
            font-size: 14px;
            flex: 1;
            min-width: 120px;
        }

        .config-button {
            padding: 8px 16px;
            background: #007bff;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: background 0.3s;
        }

        .config-button:hover {
            background: #0056b3;
        }

        .messages-container {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #fafafa;
        }

        .message {
            margin-bottom: 15px;
            display: flex;
            align-items: flex-start;
            animation: fadeIn 0.3s ease-in;
        }

        .message.user {
            justify-content: flex-end;
        }

        .message-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
            margin: 0 10px;
            flex-shrink: 0;
        }

        .message.ai .message-avatar {
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
        }

        .message.user .message-avatar {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
        }

        .message-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            font-size: 14px;
            line-height: 1.4;
            word-wrap: break-word;
        }

        .message.ai .message-content {
            background: white;
            border: 1px solid #e0e0e0;
            color: #333;
        }

        .message.user .message-content {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
        }

        .message.system .message-content {
            background: linear-gradient(135deg, #6c757d, #495057);
            color: white;
            text-align: center;
            margin: 10px auto;
            max-width: 80%;
        }

        .message.error .message-content {
            background: linear-gradient(135deg, #dc3545, #c82333);
            color: white;
            text-align: center;
            margin: 10px auto;
            max-width: 80%;
        }

        .message-time {
            font-size: 11px;
            color: #999;
            margin-top: 5px;
        }

        .input-container {
            padding: 20px;
            background: white;
            border-top: 1px solid #e9ecef;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .message-input {
            flex: 1;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
            transition: border-color 0.3s;
        }

        .message-input:focus {
            border-color: #4CAF50;
        }

        .send-button {
            padding: 12px 20px;
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 14px;
            transition: transform 0.2s;
        }

        .send-button:hover {
            transform: scale(1.05);
        }

        .send-button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .typing-indicator {
            display: none;
            align-items: center;
            padding: 12px 16px;
            background: white;
            border: 1px solid #e0e0e0;
            border-radius: 18px;
            font-size: 14px;
            color: #666;
            margin-bottom: 15px;
        }

        .typing-indicator.active {
            display: flex;
        }

        .typing-dots {
            display: flex;
            margin-left: 8px;
        }

        .typing-dots span {
            width: 4px;
            height: 4px;
            background: #999;
            border-radius: 50%;
            margin: 0 2px;
            animation: typing 1.4s infinite;
        }

        .typing-dots span:nth-child(2) { animation-delay: 0.2s; }
        .typing-dots span:nth-child(3) { animation-delay: 0.4s; }

        @keyframes typing {
            0%, 60%, 100% { transform: translateY(0); }
            30% { transform: translateY(-10px); }
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .error-message {
            background: #f8d7da;
            color: #721c24;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            font-size: 14px;
            border: 1px solid #f5c6cb;
        }

        .success-message {
            background: #d4edda;
            color: #155724;
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 15px;
            font-size: 14px;
            border: 1px solid #c3e6cb;
        }

        .quick-actions {
            display: flex;
            gap: 8px;
            margin-bottom: 15px;
            flex-wrap: wrap;
        }

        .quick-action-btn {
            padding: 6px 12px;
            background: #e9ecef;
            border: 1px solid #ced4da;
            border-radius: 15px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .quick-action-btn:hover {
            background: #007bff;
            color: white;
            border-color: #007bff;
        }

        .api-status {
            background: #f8f9fa;
            padding: 10px 15px;
            border-radius: 8px;
            font-size: 12px;
            color: #666;
            margin-bottom: 15px;
            border: 1px solid #e9ecef;
        }

        @media (max-width: 768px) {
            .chat-container {
                height: 100vh;
                max-width: 100%;
                border-radius: 0;
            }
            
            .config-panel {
                flex-direction: column;
                align-items: stretch;
            }
            
            .message-content {
                max-width: 85%;
            }
        }
    </style>
</head>
<body>
    <div class="chat-container">
        <div class="chat-header">
            <h1>🤖 AI聊天测试界面</h1>
            <p>测试豆包AI功能的交互界面</p>
            <div class="connection-status">
                <span class="status-dot" id="statusDot"></span>
                <span id="statusText">连接中...</span>
            </div>
        </div>

        <div class="config-panel">
            <input type="text" id="userIdInput" class="config-input" placeholder="用户ID (默认: 1)" value="1">
            <input type="text" id="sessionIdInput" class="config-input" placeholder="会话ID (可选)" value="">
            <button id="newSessionBtn" class="config-button">🆕 新会话</button>
            <button id="testConnectionBtn" class="config-button">🔗 测试连接</button>
            <button id="loadHistoryBtn" class="config-button">📚 加载历史</button>
            <button id="clearChatBtn" class="config-button">🗑️ 清空对话</button>
        </div>

        <div class="messages-container" id="messagesContainer">
            <div class="api-status">
                <strong>API状态:</strong> <span id="apiStatus">真实豆包AI模式</span><br>
                <strong>模型:</strong> <span id="modelInfo">doubao-1-5-thinking-pro-250415</span><br>
                <strong>服务类型:</strong> <span style="color: #28a745;">🚀 真实豆包AI API</span>
            </div>
            
            <div class="quick-actions">
                <button class="quick-action-btn" onclick="sendQuickMessage('你好，请介绍一下你自己')">👋 打招呼</button>
                <button class="quick-action-btn" onclick="sendQuickMessage('今天天气怎么样？')">🌤️ 问天气</button>
                <button class="quick-action-btn" onclick="sendQuickMessage('推荐一道美食')">🍜 推荐美食</button>
                <button class="quick-action-btn" onclick="sendQuickMessage('讲个笑话')">😄 讲笑话</button>
                <button class="quick-action-btn" onclick="sendQuickMessage('Java中的Spring Boot是什么？')">💻 问技术</button>
            </div>

            <div class="typing-indicator" id="typingIndicator">
                <span>AI正在输入</span>
                <div class="typing-dots">
                    <span></span>
                    <span></span>
                    <span></span>
                </div>
            </div>
        </div>

        <div class="input-container">
            <input type="text" id="messageInput" class="message-input" placeholder="输入消息，按Enter发送..." maxlength="500">
            <button id="sendButton" class="send-button">📤 发送</button>
        </div>
    </div>

    <script>
        class AIChatTest {
            constructor() {
                this.baseUrl = 'http://localhost:8080/api/ai';
                this.userId = 1;
                this.sessionId = '';
                this.isTyping = false;
                
                this.initializeElements();
                this.bindEvents();
                this.testConnection();
            }

            initializeElements() {
                this.elements = {
                userIdInput: document.getElementById('userIdInput'),
                sessionIdInput: document.getElementById('sessionIdInput'),
                messageInput: document.getElementById('messageInput'),
                sendButton: document.getElementById('sendButton'),
                newSessionBtn: document.getElementById('newSessionBtn'),
                testConnectionBtn: document.getElementById('testConnectionBtn'),
                loadHistoryBtn: document.getElementById('loadHistoryBtn'),
                clearChatBtn: document.getElementById('clearChatBtn'),
                messagesContainer: document.getElementById('messagesContainer'),
                typingIndicator: document.getElementById('typingIndicator'),
                statusDot: document.getElementById('statusDot'),
                statusText: document.getElementById('statusText'),
                apiStatus: document.getElementById('apiStatus'),
                modelInfo: document.getElementById('modelInfo')
            };
            }

            bindEvents() {
                // 发送消息事件
                this.elements.sendButton.addEventListener('click', () => this.sendMessage());
                this.elements.messageInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') this.sendMessage();
                });

                // 配置事件
                this.elements.newSessionBtn.addEventListener('click', () => this.createNewSession());
            this.elements.testConnectionBtn.addEventListener('click', () => this.testConnection());
            this.elements.loadHistoryBtn.addEventListener('click', () => this.loadHistory());
            this.elements.clearChatBtn.addEventListener('click', () => this.clearChat());
                
                // 输入验证
                this.elements.userIdInput.addEventListener('input', (e) => {
                    this.userId = parseInt(e.target.value) || 1;
                });
            }

            updateConnectionStatus(status, message) {
                const { statusDot, statusText } = this.elements;
                statusDot.className = `status-dot status-${status}`;
                statusText.textContent = message;
            }

            addMessage(content, type, timestamp = new Date()) {
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${type}`;
                
                const timeStr = timestamp instanceof Date ? timestamp.toLocaleTimeString('zh-CN', { 
                    hour: '2-digit', 
                    minute: '2-digit' 
                }) : new Date(timestamp).toLocaleTimeString('zh-CN', { 
                    hour: '2-digit', 
                    minute: '2-digit' 
                });
                
                let avatar = '👤';
                if (type === 'ai') avatar = '🤖';
                else if (type === 'system') avatar = '⚙️';
                else if (type === 'error') avatar = '❌';
                
                messageDiv.innerHTML = `
                    <div class="message-avatar">${avatar}</div>
                    <div>
                        <div class="message-content">${this.escapeHtml(content)}</div>
                        <div class="message-time">${timeStr}</div>
                    </div>
                `;
                
                this.elements.messagesContainer.appendChild(messageDiv);
                this.scrollToBottom();
            }

            escapeHtml(text) {
                const div = document.createElement('div');
                div.textContent = text;
                return div.innerHTML;
            }

            scrollToBottom() {
                this.elements.messagesContainer.scrollTop = this.elements.messagesContainer.scrollHeight;
            }

            showTypingIndicator() {
                this.elements.typingIndicator.classList.add('active');
                this.isTyping = true;
                this.scrollToBottom();
            }

            hideTypingIndicator() {
                this.elements.typingIndicator.classList.remove('active');
                this.isTyping = false;
            }

            showError(message) {
                const errorDiv = document.createElement('div');
                errorDiv.className = 'error-message';
                errorDiv.textContent = `❌ ${message}`;
                this.elements.messagesContainer.appendChild(errorDiv);
                this.scrollToBottom();
            }

            // 清空消息
            clearMessages() {
                this.elements.messagesContainer.innerHTML = '';
            }

            // 清空对话
            clearChat() {
                if (confirm('确定要清空当前对话吗？此操作不会删除服务器上的历史记录。')) {
                    this.clearMessages();
                    this.showSuccess('对话已清空');
                }
            }

            // 显示成功消息
            showSuccess(message) {
                this.addMessage(message, 'system', new Date());
            }

            // 显示加载状态
            showLoading(show) {
                if (show) {
                    this.elements.sendButton.disabled = true;
                    this.elements.newSessionBtn.disabled = true;
                    this.elements.testConnectionBtn.disabled = true;
                    this.elements.loadHistoryBtn.disabled = true;
                    this.elements.clearChatBtn.disabled = true;
                } else {
                    this.elements.sendButton.disabled = false;
                    this.elements.newSessionBtn.disabled = false;
                    this.elements.testConnectionBtn.disabled = false;
                    this.elements.loadHistoryBtn.disabled = false;
                    this.elements.clearChatBtn.disabled = false;
                }
            }

            showSuccess(message) {
                const successDiv = document.createElement('div');
                successDiv.className = 'success-message';
                successDiv.textContent = `✅ ${message}`;
                this.elements.messagesContainer.appendChild(successDiv);
                this.scrollToBottom();
            }

            async testConnection() {
                this.showLoading(true);
                this.updateConnectionStatus('loading', '测试中...');
                
                try {
                    // 使用POST方法调用new-session端点测试连接
                    const response = await fetch(`${this.baseUrl}/new-session?userId=1`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    const data = await response.json();
                    
                    if (response.ok && data.success) {
                        this.updateConnectionStatus('connected', '已连接');
                        this.showSuccess('连接成功！AI服务运行正常');
                        this.elements.apiStatus.textContent = '连接正常';
                    } else {
                        throw new Error(data.message || `HTTP ${response.status}`);
                    }
                } catch (error) {
                    this.updateConnectionStatus('error', '连接失败');
                    this.showError(`连接失败: ${error.message}`);
                    this.elements.apiStatus.textContent = '连接失败';
                } finally {
                    this.showLoading(false);
                }
            }

            async createNewSession() {
                this.showLoading(true);
                
                try {
                    const response = await fetch(`${this.baseUrl}/new-session?userId=${this.userId}`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });

                    const data = await response.json();
                    
                    if (response.ok && data.success) {
                        this.sessionId = data.data; // 后端返回的是data字段
                        this.clearMessages();
                        this.showSuccess('新会话创建成功');
                    } else {
                        this.showError(`创建失败: ${data.message}`);
                    }
                } catch (error) {
                    this.showError(`创建错误: ${error.message}`);
                } finally {
                    this.showLoading(false);
                }
            }

            async loadHistory() {
                if (!this.sessionId) {
                    this.showError('请先创建新会话');
                    return;
                }

                this.showLoading(true);
                
                try {
                    // 使用GET方法调用history端点，因为后端定义为@GetMapping
                    const response = await fetch(`${this.baseUrl}/history/${this.sessionId}?userId=${this.userId}`);
                    const data = await response.json();
                    
                    if (response.ok && data.success) {
                        this.clearMessages();
                        // 根据后端返回的数据结构处理
                        if (data.data && data.data.messages) {
                            data.data.messages.forEach(msg => {
                                // 根据消息类型确定发送者
                                const sender = msg.messageType === 'USER' ? 'user' : 'ai';
                                this.addMessage(msg.content, sender);
                            });
                        }
                        this.showSuccess('历史记录加载成功');
                    } else {
                        this.showError(`加载失败: ${data.message}`);
                    }
                } catch (error) {
                    this.showError(`加载错误: ${error.message}`);
                } finally {
                    this.showLoading(false);
                }
            }

            async sendMessage() {
                const messageText = this.elements.messageInput.value.trim();
                if (!messageText || this.isTyping) return;

                this.showLoading(true);
                
                try {
                    // 添加用户消息到界面
                    this.addMessage(messageText, 'user');
                    this.elements.messageInput.value = '';

                    // 发送消息到后端
                    const response = await fetch(`${this.baseUrl}/chat`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            userId: this.userId,
                            message: messageText,
                            sessionId: this.sessionId
                        })
                    });

                    const data = await response.json();
                    
                    if (response.ok && data.success) {
                        // 根据后端返回的数据结构获取回复
                        const reply = data.data && data.data.reply ? data.data.reply : data.response;
                        this.addMessage(reply, 'ai');
                        
                        // 更新会话ID
                        if (data.data && data.data.sessionId) {
                            this.sessionId = data.data.sessionId;
                        } else if (data.sessionId) {
                            this.sessionId = data.sessionId;
                        }
                    } else {
                        this.addMessage(`错误: ${data.message}`, 'error');
                    }
                } catch (error) {
                    this.addMessage(`错误: ${error.message}`, 'error');
                } finally {
                    this.showLoading(false);
                }
            }

            sendQuickMessage(message) {
                this.elements.messageInput.value = message;
                this.sendMessage();
            }
        }

        // 初始化应用
        document.addEventListener('DOMContentLoaded', () => {
            new AIChatTest();
        });

        // 全局函数供快速按钮调用
        function sendQuickMessage(message) {
            if (window.aiChatTest) {
                window.aiChatTest.sendQuickMessage(message);
            }
        }

        // 保存实例到全局
        document.addEventListener('DOMContentLoaded', () => {
            window.aiChatTest = new AIChatTest();
        });
    </script>
</body>
</html>